package goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import common.dto.goodsdto.CategoryDTO;
import common.dto.goodsdto.CategoryPercent;
import common.dto.goodsdto.GoodsDTO;
import common.dto.goodsdto.GoodsDetailDTO;
import goods.mapper.SKUGoodsMapper;
import goods.mapper.SPUGoodsMapper;
import goods.service.IGoodsService;
import goods.service.ShopServiceFeignClient;
import common.model.result.Result;
import common.model.result.ResultCodeEnum;
import common.model.goods.Sku;
import common.model.goods.Spu;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;
import common.dto.goodsdto.SkuDTO;
import common.dto.goodsdto.SpuVO;
import common.model.goods.Category;
import goods.mapper.CategoryMapper;
import goods.mapper.SpuAttributeMapper;
import common.model.goods.SpuAttribute;
import common.utils.CacheUtil;
import common.utils.RedisConstants;
import java.util.concurrent.TimeUnit;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.HashMap;
import java.util.Map;
import common.utils.OptionalUtil;
import common.exception.ExceptionHandlerUtil;
import common.exception.BusinessException;

@Service
public class GoodsServiceImpl implements IGoodsService {

    @Autowired
    private ShopServiceFeignClient shopServiceFeignClient;

    @Autowired
    private SPUGoodsMapper spuGoodsMapper;

    @Autowired
    private SKUGoodsMapper skuGoodsMapper;  

    @Autowired
    private CategoryMapper categoryMapper;
    
    @Autowired 
    private SpuAttributeMapper attributeMapper;
    
    @Autowired
    private CacheUtil cacheUtil;


    //前台
    //根据店铺id查询商品列表
    @Override
    public Result findByShopId(
            Long shopId,
            String sort,
            Integer page,
            Integer pageSize
        ) {
        // 参数校验
        if (shopId == null) {
            return Result.failure(ResultCodeEnum.BAD_REQUEST, "店铺ID不能为空");
        }
        
        return ExceptionHandlerUtil.safeExecute(() -> {
            // 查询商品列表
            // 构建查询条件
            LambdaQueryWrapper<Spu> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Spu::getShopId, shopId);
            if (sort != null) {
                queryWrapper.orderBy(true, sort.equals("asc"), Spu::getPrice);
            }
            // 分页查询
            Page<Spu> spuPage = new Page<>(
                OptionalUtil.getOrDefault(page, p -> p, 1), 
                OptionalUtil.getOrDefault(pageSize, p -> p, 10)
            );
            spuGoodsMapper.selectPage(spuPage, queryWrapper);

            // 执行查询
            List<Spu> goodsList = spuGoodsMapper.selectList(queryWrapper);
            return Result.success(goodsList);
        });
    }
    //商品详情页面
    @Override
    public Result findGoodsById(Long id) {
        // 参数校验
        if (id == null) {
            return Result.failure(ResultCodeEnum.BAD_REQUEST, "商品ID不能为空");
        }
        
        return ExceptionHandlerUtil.safeExecute(() -> {
            String key = RedisConstants.GOODS_DETAIL_KEY + id;
            String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
            
            GoodsDetailDTO goodsDetailDTO = cacheUtil.getWithCache(
                key,
                GoodsDetailDTO.class,
                () -> {
                    // 查询spu是否存在
                    Spu spu = spuGoodsMapper.selectById(id);
                    if (spu == null) {
                        return null;
                    }
                    
                    //将spu转换为dto
                    GoodsDetailDTO dto = new GoodsDetailDTO();   
                    dto.setId(spu.getId());
                    dto.setSpuCode(spu.getSpuCode());
                    dto.setShopId(spu.getShopId());
                    dto.setCategoryId(spu.getCategoryId());
                    dto.setTitle(spu.getTitle());
                    dto.setPrice(spu.getPrice());
                    dto.setMainImage(spu.getMainImage());
                    dto.setDescription(spu.getDescription());
                    
                    //根据id查询sku列表
                    List<Sku> skuList = skuGoodsMapper.selectList(
                        new LambdaQueryWrapper<Sku>().eq(Sku::getSpuId, id)
                    );
                    if (OptionalUtil.isEmpty(skuList)) {
                        return null;
                    }
                    
                    //将sku列表转换为dto
                    List<SkuDTO> skuListDTO = skuList.stream().map(sku -> {
                        SkuDTO skuDTO = new SkuDTO();
                        skuDTO.setId(sku.getId());
                        skuDTO.setSkuCode(sku.getSkuCode());
                        skuDTO.setSpecs(sku.getSpecs());
                        skuDTO.setPrice(sku.getPrice());
                        skuDTO.setCostPrice(sku.getCostPrice());
                        skuDTO.setStock(sku.getStock());
                        skuDTO.setStockThreshold(sku.getStockThreshold());
                        skuDTO.setWeight(sku.getWeight());
                        skuDTO.setVolume(sku.getVolume());
                        skuDTO.setMainImage(sku.getMainImage());
                        skuDTO.setStatus(sku.isStatus());
                        return skuDTO;
                    }).collect(Collectors.toList());    
                    
                    //将skuListDTO设置到goodsDetailDTO中
                    dto.setSkuList(skuListDTO);
                    return dto;
                },
                lockKey,
                RedisConstants.GOODS_DETAIL_TTL,
                TimeUnit.MINUTES
            );
            
            if (goodsDetailDTO == null) {
                return Result.failure(ResultCodeEnum.FAIL, "商品不存在");
            }
            
            return Result.success(goodsDetailDTO);
        });
    }
    //根据spuId查询spuVo详情
    @Override
    public Result findSpu(Long id) {
        // 参数校验
        if (id == null) {
            return Result.failure(ResultCodeEnum.BAD_REQUEST, "商品ID不能为空");
        }
        
        return ExceptionHandlerUtil.safeExecute(() -> {
            Spu spu = spuGoodsMapper.selectById(id);
            if (spu == null) {
                return Result.failure(ResultCodeEnum.FAIL, "商品不存在");
            }
            SpuVO spuVO = new SpuVO();
            BeanUtils.copyProperties(spu, spuVO);
            return Result.success(spuVO);
        });
    }
    
    //获取sku
    @Override
    public Result findSku(Long id) {
        // 参数校验
        if (id == null) {
            return Result.failure(ResultCodeEnum.BAD_REQUEST, "SKU ID不能为空");
        }
        
        return ExceptionHandlerUtil.safeExecute(() -> {
            Sku sku = skuGoodsMapper.selectById(id);
            if (sku == null) {
                return Result.failure(ResultCodeEnum.FAIL, "商品SKU不存在");
            }
            SkuDTO skuDTO = new SkuDTO();
            BeanUtils.copyProperties(sku, skuDTO);
            return Result.success(skuDTO);
        });
    }
    
    //获取商品属性
    @Override
    public Result findAttribute(Long id) {
        // 参数校验
        if (id == null) {
            return Result.failure(ResultCodeEnum.BAD_REQUEST, "商品ID不能为空");
        }
        
        return ExceptionHandlerUtil.safeExecute(() -> {
            // 查询spu是否存在
            Spu spu = spuGoodsMapper.selectById(id);
            if (spu == null) {
                return Result.failure(ResultCodeEnum.FAIL, "商品不存在");
            }
            
            // 查询spu_attribute
            List<SpuAttribute> attributes = attributeMapper.selectBySpuId(id);
            if (OptionalUtil.isEmpty(attributes)) {
                return Result.success(new ArrayList<>());
            }
            
            // 将属性分为SKU规格属性和普通属性
            Map<String, Object> result = new HashMap<>();
            List<SpuAttribute> skuSpecs = new ArrayList<>();
            List<SpuAttribute> normalAttrs = new ArrayList<>();
            
            for (SpuAttribute attr : attributes) {
                if (attr != null && attr.getIsSkuSpec()) {
                    skuSpecs.add(attr);
                } else if (attr != null) {
                    normalAttrs.add(attr);
                }
            }
            
            result.put("skuSpecs", skuSpecs);
            result.put("attributes", normalAttrs);
            
            return Result.success(result);
        });
    }
    //获取sku数据
    public Result findSkuList(Long spuId) {
        // 参数校验
        if (spuId == null) {
            return Result.failure(ResultCodeEnum.BAD_REQUEST, "商品ID不能为空");
        }
        
        return ExceptionHandlerUtil.safeExecute(() -> {
            // 查询商品是否存在
            Spu spu = spuGoodsMapper.selectById(spuId);
            if (spu == null) {
                return Result.failure(ResultCodeEnum.FAIL,"商品不存在");
            }
            // 查询sku列表
            LambdaQueryWrapper<Sku> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Sku::getSpuId, spuId);
            List<Sku> skuList = skuGoodsMapper.selectList(queryWrapper.eq(Sku::isStatus, true));
            if (OptionalUtil.isEmpty(skuList)) {
                return Result.failure(ResultCodeEnum.FAIL,"sku异常");
            }
            return Result.success(skuList);
        });
    }
    //获取推荐商品
    @Override
    public Result recommend() {
        return ExceptionHandlerUtil.safeExecute(() -> {
            // 获取所有商品
            List<Spu> recommendList = spuGoodsMapper.selectList(new LambdaQueryWrapper<Spu>().eq(Spu::isStatus, true));
            if (OptionalUtil.isEmpty(recommendList)) {
                return Result.failure(ResultCodeEnum.FAIL,"商品不存在");
            }
            //将推荐商品列表转换为dto
            List<SpuVO> recommendListDTO = recommendList.stream()
                .filter(spu -> spu != null)  // 过滤null值
                .map(spu -> {
                    SpuVO spuVO = new SpuVO();
                    spuVO.setId(spu.getId());
                    spuVO.setShopId(spu.getShopId());
                    spuVO.setSpuCode(spu.getSpuCode());
                    spuVO.setTitle(spu.getTitle());
                    spuVO.setPrice(spu.getPrice());
                    spuVO.setMainImage(spu.getMainImage());
                    spuVO.setDescription(spu.getDescription());
                    return spuVO;
                }).collect(Collectors.toList());
            return Result.success(recommendListDTO);
        });
    }
    //获取分类表
    @Override
    public Result getCategory() {
        // 查询1级level的分类
        List<Category> categoryList = categoryMapper
            .selectList(new LambdaQueryWrapper<Category>().eq(Category::getLevel, 1));
        List<CategoryDTO> levelOneDTOs = new ArrayList<>();
        
        // 遍历一级分类，根据其id查询其子分类
        for (Category category : categoryList) {
            CategoryDTO categoryDTO = new CategoryDTO();
            BeanUtils.copyProperties(category, categoryDTO);
            
            // 如果不是叶子节点，继续查询子分类
            if (!category.getIsLeaf()) {
                // 查询二级分类
                List<Category> secondLevelList = categoryMapper
                    .selectList(new LambdaQueryWrapper<Category>()
                        .eq(Category::getParentId, category.getId())
                        .eq(Category::getLevel, 2));
                List<CategoryDTO> secondLevelDTOs = new ArrayList<>();
                
                // 遍历二级分类，将其添加到一级分类的children中
                for (Category secondCategory : secondLevelList) {
                    CategoryDTO secondCategoryDTO = new CategoryDTO();
                    BeanUtils.copyProperties(secondCategory, secondCategoryDTO);
                    secondLevelDTOs.add(secondCategoryDTO);
                }
                categoryDTO.setChildren(secondLevelDTOs);
            }
            levelOneDTOs.add(categoryDTO);
        }
        
        return Result.success(levelOneDTOs);
    }
    //搜索商品
    @Override
    public Result search(String data, Pageable pageable) {
        // 参数校验
        if (OptionalUtil.isEmpty(data)) {
            return Result.failure(ResultCodeEnum.BAD_REQUEST, "搜索关键词不能为空");
        }
        if (pageable == null) {
            pageable = Pageable.unpaged(); // 使用默认分页
        }
        
        final Pageable finalPageable = pageable; // 在lambda中使用
        
        return ExceptionHandlerUtil.safeExecute(() -> {
            // 1. 根据商品名称模糊查询
            LambdaQueryWrapper<Spu> nameQueryWrapper = new LambdaQueryWrapper<>();
            nameQueryWrapper.like(Spu::getTitle, data);

            List<Spu> nameResultList = spuGoodsMapper.selectList(nameQueryWrapper.eq(Spu::isStatus, true));

            // 2. 根据分类名称模糊查询获取分类ID
            LambdaQueryWrapper<Category> categoryQueryWrapper = new LambdaQueryWrapper<>();
            categoryQueryWrapper.like(Category::getName, data);
            List<Category> categoryList = categoryMapper.selectList(null);
            
            // 获取所有匹配的分类ID
            List<Long> categoryIds = OptionalUtil.isNotEmpty(categoryList) ? 
                categoryList.stream()
                    .filter(c -> c != null) // 过滤null值
                    .map(Category::getId)
                    .collect(Collectors.toList())
                : new ArrayList<>();

            // 3. 根据分类ID查询商品
            List<Spu> categoryResultList = new ArrayList<>();
            if (!categoryIds.isEmpty()) {
                LambdaQueryWrapper<Spu> categoryIdQueryWrapper = new LambdaQueryWrapper<>();
                categoryIdQueryWrapper.in(Spu::getCategoryId, categoryIds);
                categoryResultList = spuGoodsMapper.selectList(categoryIdQueryWrapper.eq(Spu::isStatus, true));
            }

            // 4. 合并结果并去重
            Set<Spu> mergedSet = new HashSet<>();
            if (OptionalUtil.isNotEmpty(nameResultList)) {
                mergedSet.addAll(nameResultList);
            }
            if (OptionalUtil.isNotEmpty(categoryResultList)) {
                mergedSet.addAll(categoryResultList);
            }
            List<Spu> mergedList = new ArrayList<>(mergedSet);

            // 5. 分页处理
            int pageSize = finalPageable.getPageSize();
            int pageNumber = finalPageable.getPageNumber();
            int startIndex = pageNumber * pageSize;
            int endIndex = Math.min(startIndex + pageSize, mergedList.size());
            
            // 如果起始索引超出列表范围，返回空列表
            if (startIndex >= mergedList.size()) {
                return Result.success(new ArrayList<>());
            }
            
            // 获取分页后的子列表
            List<Spu> pagedList = mergedList.subList(startIndex, endIndex);

            // 6. 转换为SpuVO列表
            List<SpuVO> resultList = pagedList.stream()
                .filter(spu -> spu != null) // 过滤null值
                .map(spu -> {
                    SpuVO spuVO = new SpuVO();
                    spuVO.setId(spu.getId());
                    spuVO.setShopId(spu.getShopId());
                    spuVO.setSpuCode(spu.getSpuCode());
                    spuVO.setTitle(spu.getTitle());
                    spuVO.setPrice(spu.getPrice());
                    spuVO.setMainImage(spu.getMainImage());
                    spuVO.setDescription(spu.getDescription());
                    
                    // 获取分类名称
                    Category category = categoryMapper.selectById(spu.getCategoryId());
                    if (category != null) {
                        spuVO.setCategoryName(category.getName());
                    }
                    
                    return spuVO;
                }).collect(Collectors.toList());

            // 7. 构建分页结果
            Map<String, Object> result = new HashMap<>();
            result.put("total", mergedList.size());
            result.put("pages", (mergedList.size() + pageSize - 1) / pageSize);
            result.put("current", pageNumber + 1); // Spring Data的页码从0开始，这里+1转换为从1开始
            result.put("size", pageSize);
            result.put("records", resultList);

            return Result.success(result);
        });
    }

    //更新sku库存
    @Override
    public Result updateSkuStock(Sku sku) {
        skuGoodsMapper.updateById(sku);
        return Result.success("商品修改成功");
    }

    //后台
    //获取商品分类占比
    public Result getCategoryPercent() {
        List<CategoryPercent> categoryPercents = new ArrayList<>();
        Map<Long, CategoryPercent> levelOneCategoryMap = new HashMap<>();

        // 1. 获取所有一级分类
        List<Category> levelOneCategories = categoryMapper.selectList(
            new LambdaQueryWrapper<Category>().eq(Category::getLevel, 1)
        );
        
        // 初始化一级分类的统计对象
        for (Category levelOneCategory : levelOneCategories) {
            CategoryPercent categoryPercent = new CategoryPercent();
            categoryPercent.setCategoryName(levelOneCategory.getName());
            categoryPercent.setGoodsNumber(0); // 初始化商品数量为0
            levelOneCategoryMap.put(levelOneCategory.getId(), categoryPercent);
            categoryPercents.add(categoryPercent);
        }

        // 2. 获取所有二级分类
        List<Category> levelTwoCategories = categoryMapper.selectList(
            new LambdaQueryWrapper<Category>().eq(Category::getLevel, 2)
        );

        // 3. 遍历二级分类，统计商品数量并累加到对应的一级分类
        for (Category levelTwoCategory : levelTwoCategories) {
            // 查询该二级分类下的商品数量
            LambdaQueryWrapper<Spu> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Spu::getCategoryId, levelTwoCategory.getId());
            Long count = spuGoodsMapper.selectCount(queryWrapper);
            Integer goodsCount = count.intValue();
            
            // 获取该二级分类的父级分类（一级分类）
            Long parentId = levelTwoCategory.getParentId();
            
            // 将商品数量累加到对应的一级分类中
            CategoryPercent parentCategoryPercent = levelOneCategoryMap.get(parentId);
            if (parentCategoryPercent != null) {
                parentCategoryPercent.setGoodsNumber(
                    parentCategoryPercent.getGoodsNumber() + goodsCount
                );
            }
        }

        // 4. 返回一级分类占比列表
        return Result.success(categoryPercents);
    }

    //获取商品列表
    @Override
    public Result getGoodsList(Integer page, Integer pageSize) {
        return ExceptionHandlerUtil.safeExecute(() -> {
            // 创建分页对象 - 确保参数不为空
            Page<Spu> spuPage = new Page<>(
                OptionalUtil.getOrDefault(page, p -> p, 1), 
                OptionalUtil.getOrDefault(pageSize, p -> p, 10)
            );
            
            // 执行分页查询
            spuGoodsMapper.selectPage(spuPage, null);
            
            // 获取分页查询结果
            List<Spu> spuList = spuPage.getRecords();
            
            // 转换为GoodsDTO列表，同时处理可能的空值
            List<GoodsDTO> goodsDTOList = OptionalUtil.isNotEmpty(spuList) ? 
                spuList.stream()
                    .filter(spu -> spu != null) // 过滤null值
                    .map(spu -> {
                        GoodsDTO goodsDTO = new GoodsDTO();
                        goodsDTO.setSpu(spu);
                        
                        //根据spu的id查询sku列表
                        List<Sku> skuList = skuGoodsMapper.selectList(
                            new LambdaQueryWrapper<Sku>().eq(Sku::getSpuId, spu.getId())
                        );
                        goodsDTO.setSkuList(OptionalUtil.isNotEmpty(skuList) ? skuList : new ArrayList<>());
                        
                        return goodsDTO;
                    }).collect(Collectors.toList())
                : new ArrayList<>();
            
            // 创建分页结果对象
            common.dto.PageResult<GoodsDTO> pageResult = new common.dto.PageResult<>();
            pageResult.setTotal(spuPage.getTotal());
            pageResult.setItems(goodsDTOList);
            
            return Result.success(pageResult);
        });
    }
    //新增商品sku
    @Override
    public Result addSku(Sku sku) {
        skuGoodsMapper.insert(sku);
        return Result.success("商品添加成功");
    }
    //新增商品
    @Override
    public Result add(GoodsDTO goods) {
        System.out.println(goods);
        // 参数校验
        if (goods == null || goods.getSpu() == null) {
            return Result.failure(ResultCodeEnum.BAD_REQUEST, "商品信息不能为空");
        }
        
        return ExceptionHandlerUtil.safeExecute(() -> {
            try {
                // 完全创建新的SPU对象，不要使用前端传来的对象
                Spu spu = new Spu();
                
                // 只复制必要字段，不设置ID
                spu.setSpuCode(goods.getSpu().getSpuCode());
                spu.setShopId(goods.getSpu().getShopId());
                spu.setCategoryId(goods.getSpu().getCategoryId());
                spu.setTitle(goods.getSpu().getTitle());
                spu.setPrice(goods.getSpu().getPrice());
                spu.setMainImage(goods.getSpu().getMainImage());
                spu.setStatus(goods.getSpu().isStatus());
                spu.setDeleted(goods.getSpu().isDeleted());
                spu.setDescription(goods.getSpu().getDescription());
                spu.setDetailHtml(goods.getSpu().getDetailHtml());
                
                // 处理 subImages 字段
                String subImages = OptionalUtil.getOrDefault(goods.getSpu().getSubImages(), s -> s, "");
                if (subImages.isEmpty() || "[]".equals(subImages) || "{}".equals(subImages)) {
                    // 如果为空数组或空对象，设置为 null，避免 MySQL 报错
                    spu.setSubImages(null);
                } else {
                    spu.setSubImages(subImages);
                }
                
                // 处理 specTemplate 字段
                String specTemplate = OptionalUtil.getOrDefault(goods.getSpu().getSpecTemplate(), s -> s, "");
                if (specTemplate.isEmpty() || "[]".equals(specTemplate) || "{}".equals(specTemplate)) {
                    // 如果为空，设置一个默认的空JSON对象
                    spu.setSpecTemplate("{}");
                } else {
                    spu.setSpecTemplate(specTemplate);
                }
                
                // 确保ID为null
                spu.setId(null);
                
                // 插入SPU数据，这里会返回插入条数
                int insertCount = spuGoodsMapper.insert(spu);
                
                if (insertCount <= 0) {
                    return Result.failure(ResultCodeEnum.FAIL, "添加商品SPU失败");
                }
                
                // 获取返回的SPU ID
                Long spuId = spu.getId();
                if (spuId == null) {
                    return Result.failure(ResultCodeEnum.FAIL, "获取商品SPU ID失败");
                }
                
                // 添加SKU数据
                if (OptionalUtil.isNotEmpty(goods.getSkuList())) {
                    for (Sku sku : goods.getSkuList()) {
                        if (sku != null) {
                            // 创建全新的SKU对象
                            Sku newSku = new Sku();
                            
                            // 设置关联的SPUID
                            newSku.setSpuId(spuId);
                            
                            // 设置其他字段
                            newSku.setSkuCode(sku.getSkuCode());
                            newSku.setSpecs(sku.getSpecs());
                            newSku.setPrice(sku.getPrice());
                            newSku.setCostPrice(sku.getCostPrice());
                            newSku.setStock(sku.getStock());
                            newSku.setStockThreshold(sku.getStockThreshold());
                            newSku.setWeight(sku.getWeight());
                            newSku.setVolume(sku.getVolume());
                            newSku.setMainImage(sku.getMainImage());
                            newSku.setStatus(sku.isStatus());
                            
                            // 确保ID为null
                            newSku.setId(null);
                            
                            // 插入SKU
                            skuGoodsMapper.insert(newSku);
                        }
                    }
                }
                
                return Result.success("商品添加成功");
                
            } catch (Exception e) {
                // 记录详细错误信息
                e.printStackTrace();
                return Result.failure(ResultCodeEnum.FAIL, "添加商品失败: " + e.getMessage());
            }
        });
    }
    //修改商品sku
    @Override
    public Result updateSku(Sku sku) {
        skuGoodsMapper.updateById(sku);
        return Result.success("商品修改成功");
    }
    //修改商品spu
    @Override
    public Result updateSpu(Spu spu) {
        // 参数校验
        if (spu == null || spu.getId() == null) {
            return Result.failure(ResultCodeEnum.BAD_REQUEST, "商品ID不能为空");
        }
        
        return ExceptionHandlerUtil.safeExecute(() -> {
            // 验证 subImages 字段，确保它是有效的 JSON 格式
            if (spu.getSubImages() != null && (spu.getSubImages().isEmpty() || "[]".equals(spu.getSubImages()) || "{}".equals(spu.getSubImages()))) {
                // 如果为空数组或空对象，设置为 null，避免 MySQL 报错
                spu.setSubImages(null);
            }
            
            spuGoodsMapper.updateById(spu);
            return Result.success("商品修改成功");
        });
    }
    //删除商品
    @Override
    public Result delete(Long id) {
        // 参数校验
        if (id == null) {
            return Result.failure(ResultCodeEnum.BAD_REQUEST, "商品ID不能为空");
        }
        
        return ExceptionHandlerUtil.safeExecute(() -> {
            // 先删除商品sku
            skuGoodsMapper.delete(new LambdaQueryWrapper<Sku>().eq(Sku::getSpuId, id));
            // 再删除商品spu
            spuGoodsMapper.deleteById(id);
            return Result.success("商品删除成功");
        });
    }
    //删除商品sku
    @Override
    public Result deleteSku(Long id) {
        skuGoodsMapper.deleteById(id);
        return Result.success("商品删除成功");
    }
    //添加分类
    @Override
    public Result addCategory(Category category) {
        categoryMapper.insert(category);
        return Result.success("分类添加成功");
    }
    //更新分类
    @Override
    public Result updateCategory(Category category) {
        categoryMapper.updateById(category);
        return Result.success("分类更新成功");
    }
    //删除分类
    @Override
    public Result deleteCategory(Long id) {
        categoryMapper.deleteById(id);
        return Result.success("分类删除成功");
    }   


    //获取所有二级分类
    @Override
    public Result getSecondCategory() {
        return Result.success(categoryMapper.selectList(new LambdaQueryWrapper<Category>().eq(Category::getLevel, 2)));
    }

    //获取分类列表
    @Override
    public Result getCategoryList() {
        // 查询1级level的分类
        List<Category> categoryList = categoryMapper
            .selectList(new LambdaQueryWrapper<Category>().eq(Category::getLevel, 1));
        List<CategoryDTO> levelOneDTOs = new ArrayList<>();
        
        // 遍历一级分类，根据其id查询其子分类
        for (Category category : categoryList) {
            CategoryDTO categoryDTO = new CategoryDTO();
            BeanUtils.copyProperties(category, categoryDTO);
            
            // 如果不是叶子节点，继续查询子分类
            if (!category.getIsLeaf()) {
                // 查询二级分类
                List<Category> secondLevelList = categoryMapper
                    .selectList(new LambdaQueryWrapper<Category>()
                        .eq(Category::getParentId, category.getId())
                        .eq(Category::getLevel, 2));
                List<CategoryDTO> secondLevelDTOs = new ArrayList<>();
                
                // 遍历二级分类，将其添加到一级分类的children中
                for (Category secondCategory : secondLevelList) {
                    CategoryDTO secondCategoryDTO = new CategoryDTO();
                    BeanUtils.copyProperties(secondCategory, secondCategoryDTO);
                    secondLevelDTOs.add(secondCategoryDTO);
                }
                categoryDTO.setChildren(secondLevelDTOs);
            }
            levelOneDTOs.add(categoryDTO);
        }
        
        return Result.success(levelOneDTOs);
    }

    //修改商品上下架状态
    @Override
    public Result updateSpuStatus(Long id, Boolean status) {
        // 参数校验
        if (id == null) {
            return Result.failure(ResultCodeEnum.BAD_REQUEST, "商品ID不能为空");
        }
        if (status == null) {
            return Result.failure(ResultCodeEnum.BAD_REQUEST, "商品状态不能为空");
        }
        
        return ExceptionHandlerUtil.safeExecute(() -> {
            spuGoodsMapper.update(null, new LambdaUpdateWrapper<Spu>().eq(Spu::getId, id).set(Spu::isStatus, status));
            return Result.success("商品上下架状态修改成功");
        });
    }
}